import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import EditTemplate from '@/components/EditTemplate';
import { Table, Card, Row, Button, Modal, Input, message } from 'antd';
import { timeFormat } from '@/utils/common';
import { getStatus } from '@/utils/business';
import AuthButton from '@/components/AuthButton';
import Status from '@/pages/components/Status';
import CapitalSource from '@/pages/components/capitalSource';
const { TextArea } = Input;

const BuildEdit = ({ location, dispatch, uuid, update }: any) => {
  const [detail, setDetail] = useState(null);
  const { id, readOnly, isApprove = false, fromType = 7 } = location.query;
  const [showModal, setshowModal] = useState(false);
  const pointType = { 3: 'PLAN', 1: 'ANNUAL', 7: 'MONEY' }[fromType];
  const [approveList, setapproveList] = useState([]);
  const [comment, setcomment] = useState('');
  const saveUrl = '/api/project/report/v1/moneyReport/create';
  useEffect(() => {
    if (id) {
      if (update === false) return;
      dispatch({
        type: '$request/post',
        payload: {
          url: '/api/project/report/v1/moneyReport/detail',
          data: {
            uuid: uuid || id,
            page: 0,
            size: 10,
          },
        },
      }).then(res => {
        console.log('储备项目申报详情：', res);
        getApproveList(res.uuid);
        setDetail({
          ...res,
          ...res.project,
          createTime: timeFormat(res.createTime),
        });
      });
    }
  }, []);
  const projectChange = (uuid, data) => {
    if (update === false) return;
    dispatch({
      type: '$request/post',
      payload: {
        url: '/api/project/report/v1/moneyReport/project/query',
        data: { uuid },
      },
    }).then(list => {
      const res = list.find(item => item.uuid == uuid);
      res.createTime = timeFormat(new Date(), 'YYYY-MM-DD');
      setDetail(res);
    });
  };
  const filters = [
    {
      title: '基础信息',
      list: [
        {
          key: id ? 'name' : 'projectUuid',
          type: id ? 'text' : 'select',
          label: '项目名称',
          asyncopt: {
            url: '/api/project/report/v1/moneyReport/project/query',
          },
          prop: {
            onChange: (uuid, data) => {
              console.log('uuid', uuid);
              projectChange(uuid, data);
            },
          },
          span: 12,
        },
        {
          key: 'code',
          type: 'text',
          label: '项目代码',
          span: 12,
        },
        {
          key: 'ownerOrgUnit',
          type: 'text',
          label: '业主单位',
          span: 12,
        },
        {
          key: 'createTime',
          type: 'text',
          label: '申请日期',
          span: 12,
        },
        {
          key: 'fundSource',
          type: 'custom',
          label: '申请金额',
          render: <CapitalSource readOnly={readOnly} />,
          rules: [{ required: true }],
          span: 24,
        },
        {
          key: 'reason',
          type: 'textarea',
          label: '申请原因',
          rules: [{ required: true }],
          span: 24,
        },
        {
          key: 'fileList',
          type: 'upload',
          label: '申请附件',
          span: 24,
        },
      ],
    },
  ];
  const columns = [
    { title: '审批节点', dataIndex: 'name', width: 150 },
    {
      title: '审批时间',
      dataIndex: 'createTime',
      width: 250,
      render: (text, data) => (getStatus(data, 3) ? text : ''),
    },
    {
      title: '审批结果',
      dataIndex: 'result',
      width: 150,
      render: (text, data) => <Status data={data} type={3} />,
    },
    { title: '审批意见', dataIndex: 'comment' },
  ];
  const getApproveList = id => {
    //---------------- 获取审批节点 ---------
    readOnly &&
      dispatch({
        type: '$request/post',
        payload: {
          url: '/api/project/approve/v1/result/list',
          data: { uuid: id, pointType: 'MONEY' },
        },
      }).then(res => {
        const list = res.map(item => {
          return {
            ...item,
            createTime: timeFormat(item.createTime),
            name: item.department.name + '审批',
          };
        });
        setapproveList(list);
      });
  };
  const preproccess = data => {
    const fileUuidList = data.fileList
      ? data.fileList.map(item => item.uuid)
      : [];
    return {
      ...data,
      fileUuidList,
      amount: parseFloat(data.amount),
    };
  };
  const handleResult = type => {
    if (!comment && !type) {
      message.error('拒绝时请输入审批意见');
      return;
    }
    if (!detail || !detail.approveResult) {
      return message.error('项目信息不正确');
    }
    dispatch({
      type: '$request/post',
      payload: {
        url: '/api/project/report/v1/moneyReport/approve',
        data: {
          projectType: 'PLAN',
          comment: comment,
          result: type,
          uuid: detail.approveResult.uuid,
        },
      },
    }).then(() => {
      message.success('审批成功');
      dispatch({ type: '$router/back' });
    });
  };
  return (
    <div>
      <EditTemplate
        filters={filters}
        initialValues={detail}
        updateUrl={saveUrl}
        readOnly={readOnly}
        preproccess={preproccess}
        footer={
          isApprove && (
            <Button type="primary" onClick={() => setshowModal(true)}>
              审批
            </Button>
          )
        }
      />
      {readOnly && (
        <Card title="审批信息">
          <Table
            bordered
            tableLayout="fixed"
            dataSource={approveList}
            columns={columns}
          ></Table>
        </Card>
      )}
      <Modal
        title="审批意见"
        visible={showModal}
        okText="通过"
        cancelText="拒绝"
        onCancel={() => setshowModal(false)}
        footer={[
          <AuthButton
            key="back"
            onClick={() => handleResult(false)}
            role="examine_project_funding"
          >
            拒绝
          </AuthButton>,
          <AuthButton
            type="primary"
            onClick={() => handleResult(true)}
            role="examine_project_funding"
          >
            通过
          </AuthButton>,
        ]}
      >
        <TextArea
          placeholder="审批意见，拒绝时必填"
          value={comment}
          onChange={e => setcomment(e.target.value)}
        />
      </Modal>
    </div>
  );
};

export default connect((state: any) => state.auth)(BuildEdit);
